//
//  STLoginView.swift
//  iPhone
//
//  Created by Toj on 4/19/23.
//

import UIKit

protocol STLoginViewDelegate: NSObjectProtocol {
    func loginViewDidTapOthers(_ loginView: STLoginView)
    func loginViewDidTapLogin(_ loginView: STLoginView)
    func loginViewDidTapClose(_ loginView: STLoginView)
}

class STLoginView: UIView {
    
    weak var delegate: STLoginViewDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupMakeAddSubviews()
        setupMakeInitialize()
        setupMakeNotification()
        setupMakeLayoutSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /* 背景View */
    private lazy var backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.tt_alpha(0.5)
        
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(didTapBackground))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    /* 展示内容 */
    private lazy var contentView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        view.cm_corner(radius: 24, corners: [.layerMinXMinYCorner, .layerMaxXMinYCorner])
        
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(didTapEndEditing))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    /* 关闭按钮 */
    private lazy var closeButton: UIButton = {
        let view = UIButton()
        view.setImage("com_close_lucencyGray".img_resource, for: .normal)
        view.addTarget(self, action: #selector(didTapClosed), for: .touchUpInside)
        return view
    }()
    
    /* 标题 */
    private lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.textColor = "#333333".to_color
        view.font = 20.to_boldFont
        view.textAlignment = .center
        view.numberOfLines = 0
        view.text = "NewSignIn_title1".localized()
        return view
    }()
    
    /* 选择国家 */
    private lazy var countryImageView: UIImageView = {
        let view = UIImageView()
        view.image = "com_country_others".img_resource
        return view
    }()
    private lazy var arrowImageView: UIImageView = {
        let view = UIImageView()
        view.image = "com_arrow_area_down".img_resource
        return view
    }()
    private lazy var countryButton: UIButton = {
        let view = UIButton()
        view.addTarget(self, action: #selector(didTapSelectedCountry), for: .touchUpInside)
        return view
    }()
    
    /* 账号文本框 */
    private lazy var accountTextField: FMTextField = {
        let view = FMTextField()
        
        view.lineNormalColor = "#999999".to_color
        
        view.textField.delegate = self
        view.textField.inputAccessoryView = nil
        view.textField.keyboardType = .asciiCapable // .emailAddress
        view.textField.clearButtonMode = .whileEditing // 清空按钮
        view.textField.font = 16.to_boldFont
        view.textField.textColor = .black
        
        let ptext = "login_input_user".localized()
        let attributedPlaceholder = ptext.to_attributedString(font:  14.to_systemFont, color: "#DDDDDD".to_color)
        view.textField.attributedPlaceholder = attributedPlaceholder
        
        return view
    }()
    
    /* 错误提示 */
    private lazy var faildTipsLabel: UILabel = {
        let view = UILabel()
        view.textColor = "#FF0000".to_color
        view.font = 10.to_boldFont
        view.numberOfLines = 0
        view.text = "mailbox_not_correct_format".localized()
        return view
    }()
    
    /* 登录按钮 */
    private lazy var signInButton: UIButton = {
        let view = UIButton()
        view.backgroundColor = "#0087EB".to_color
        view.titleLabel?.font = 14.to_boldFont
        view.setTitleColor(.white, for: .normal)
        view.setTitle("NewSignIn_title1".localized(), for: .normal)
        let width = CGFloat.sr_width - 80
        view.frame = CGRect(origin: .zero, size: CGSize(width: width, height: 32.ui_scale))
        view.addTarget(self, action: #selector(didTapLogin), for: .touchUpInside)
        view.cm_cornerRadius = 16.ui_scale
        return view
    }()
    
    /* 第三方登录方式 */
    private lazy var thirdView: UIView = {
        let view = UIView()
        view.backgroundColor = .random
        return view
    }()

    let thirdLeftLineView: UIView = {
        let view = UIView()
        view.backgroundColor = 0xDDDDDD.to_color
        return view
    }()
    let thirdLoginTitleLabel: UILabel = {
        let view = UILabel()
        view.text = "NewSignIn_OtherWays".localized()
        view.textColor = "#666666".to_color
        view.font = 12.to_systemFont
        return view
    }()
    let thirdRightLineView: UIView = {
        let view = UIView()
        view.backgroundColor = 0xDDDDDD.to_color
        return view
    }()
    
    private lazy var privacyView: STSignInPrivacyView = {
        let view = STSignInPrivacyView()
        return view
    }()
}

// MARK: - 点击事件
@objc private extension STLoginView {
    
    func didTapBackground() {
        print("-->toj: func:" + #function)
        didTapClosed()
    }
    
    func didTapClosed() {
        print("-->toj: func:" + #function)
        didTapEndEditing()
        delegate?.loginViewDidTapClose(self)
    }
    
    func didTapLogin() {
        print("-->toj: func:" + #function)
        didTapEndEditing()
        
        delegate?.loginViewDidTapLogin(self)
    }
    
    func didTapSelectedCountry() {
        print("-->toj: func:" + #function)
        didTapEndEditing()
    }
    
    func didTapEndEditing() {
        endEditing(true)
    }
    
    func keyboardWillShow(notification: Notification) {
        guard let info = notification.userInfo as NSDictionary?
        else { return }
        
        let frameValue = info[UIResponder.keyboardFrameEndUserInfoKey]
        // 得到键盘frame
        let keyboardFrame = (frameValue as AnyObject).cgRectValue
        let kbHeight = keyboardFrame?.size.height ?? 303
        
        let kbDuration = info[UIResponder.keyboardAnimationDurationUserInfoKey]
        var duration = kbDuration as? TimeInterval ?? 0
        if duration == 0 { duration = 0.25 }
        
        setupMakeLayoutContentView(kbHeight)
        UIView.animate(withDuration: duration) {
            self.layoutIfNeeded()
        }
    }
    
    func keyboardWillHide(notification: Notification) {
        guard let info = notification.userInfo as NSDictionary?
        else { return }
        
        let kbDuration = info[UIResponder.keyboardAnimationDurationUserInfoKey]
        var duration = kbDuration as? TimeInterval ?? 0
        if duration == 0 { duration = 0.25 }
        
        setupMakeLayoutContentView()
        UIView.animate(withDuration: duration) {
            self.layoutIfNeeded()
        }
    }
}

// MARK: - Public
extension STLoginView {
    
    func show() {
        clearAccount()
        isHidden = false
        setupMakeLayoutOtherViews()
    }
    
    func hide() {
        isHidden = true
    }
}

// MARK: - Private
private extension STLoginView {
    
    func clearAccount() {
        accountTextField.text = ""
    }
}

extension STLoginView: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        didTapLogin()
        
        return true
    }
}

// MARK: - 初始化设置
private extension STLoginView {
    
    func setupMakeAddSubviews() {
        
        addSubview(backgroundView)
        
        addSubview(contentView)
        // 服务协议
        addSubview(privacyView)
        
        // 标题
        contentView.addSubview(titleLabel)
        // 关闭按钮
        contentView.addSubview(closeButton)
        // 选择国家
        contentView.addSubview(countryImageView)
        contentView.addSubview(arrowImageView)
        contentView.addSubview(countryButton)
        // 输入账号
        contentView.addSubview(accountTextField)
        // 登录按钮
        contentView.addSubview(signInButton)
        // 第三方登录方式
        contentView.addSubview(thirdView)
        // 错误提示
        contentView.addSubview(faildTipsLabel)
    }
    
    func setupMakeLayoutContentView(_ bottom: CGFloat = 0) {
        let size = contentView.frame.size
        contentView.snp.remakeConstraints { make in
            make.left.right.equalTo(self)
            make.height.equalTo(size.height)
            make.bottom.equalTo(-bottom)
        }
    }
    
    func setupMakeLayoutOtherViews() {
        STFunctionManager.manager.hasThird = arc4random_uniform(2) == 1
        let hasThird = STFunctionManager.manager.hasThird
        let height = hasThird ? 400 : 300
        print("-->toj: hasThird:" + "\(hasThird)")
        contentView.snp.remakeConstraints { make in
            make.left.right.equalTo(self)
            make.height.equalTo(height.ui_mscale)
            make.bottom.equalTo(0)
        }
     
        thirdView.isHidden = !hasThird
        guard !thirdView.isHidden else { return }
        thirdView.snp.remakeConstraints { make in
            make.left.right.equalTo(contentView)
            make.height.equalTo(100.ui_mscale)
            make.bottom.equalTo(privacyView.snp.top)
        }
    }
    
    func setupMakeLayoutSubviews() {
        
        backgroundView.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
        
        closeButton.snp.makeConstraints { make in
            make.right.top.equalTo(contentView)
            make.width.equalTo(48)
            make.height.equalTo(48)
        }
        titleLabel.snp.makeConstraints { make in
            make.left.right.equalTo(contentView).inset(20)
            make.top.equalTo(contentView)
            make.height.equalTo(100.ui_mscale)
        }
        
        countryButton.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.width.equalTo(48)
            make.height.equalTo(48)
            make.top.equalTo(titleLabel.snp.bottom)
        }
        countryImageView.snp.makeConstraints { make in
            make.left.centerY.equalTo(countryButton)
            make.height.equalTo(24)
            make.width.equalTo(24)
        }
        arrowImageView.snp.makeConstraints { make in
            make.right.centerY.equalTo(countryButton)
            make.height.equalTo(24)
            make.width.equalTo(24)
        }
        
        accountTextField.snp.makeConstraints { make in
            make.left.equalTo(countryButton.snp.right).offset(12)
            make.right.equalTo(snp.right).offset(-26)
            make.height.equalTo(30)
            make.centerY.equalTo(countryButton)
        }
        
        faildTipsLabel.snp.makeConstraints { make in
            make.left.right.equalTo(accountTextField)
            make.top.equalTo(accountTextField.snp.bottom).offset(4)
        }
        
        let size = signInButton.frame.size
        signInButton.snp.remakeConstraints { make in
            make.centerX.equalTo(contentView)
            make.top.equalTo(countryButton.snp.bottom).offset(28.ui_mscale)
            make.width.equalTo(size.width)
            make.height.equalTo(size.height)
        }
        
        privacyView.snp.makeConstraints { make in
            make.left.right.equalTo(signInButton)
            make.height.equalTo(84.ui_mscale)
            make.bottom.equalTo(contentView)
        }
        
        setupMakeLayoutOtherViews()
    }
    
    func setupMakeInitialize() {
        
    }
    
    func setupMakeNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
}
